package com.peas.platform.common.core.configuration;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.convert.converter.Converter;
import org.springframework.lang.NonNull;

import java.text.DateFormat;
import java.time.LocalDateTime;
import java.util.Date;

@Slf4j
public class ConverterLocalDateTime implements Converter<String, LocalDateTime> {

    @Override
    public LocalDateTime convert(@NonNull String source) {
        log.debug("ConverterLocalDateTime, source:" + source);
        if (StrUtil.isBlank(source)) {
            return null;
        }
        if ("null".equalsIgnoreCase(source)) {
            return null;
        }
        try {
            if (source.matches("^\\d{13}$")) {
                Date date = new Date(Long.parseLong(source));
                return LocalDateTimeUtil.of(date);
            }
            return parse(source);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    @SneakyThrows
    private LocalDateTime parseLocalDateTime(String text, String pattern) {
        if (StrUtil.isBlank(text)) {
            return null;
        }
        DateFormat formatter = DateFormatReg.getDateFormat(pattern);
        Date date = formatter.parse(text);
        return LocalDateTimeUtil.of(date);
    }

    @SneakyThrows
    private LocalDateTime parse(String text) {
        if (StrUtil.isBlank(text)) {
            return null;
        }
        return parseLocalDateTime(text, DateFormatReg.getPattern(text));
    }

}
